// iconLoader.js - 自动为指定元素添加图标的工具
import Vue from 'vue'
// 导入字体文件
import iconFontWoff2 from '@/assets/font/iconfont.woff2'
import iconFontWoff from '@/assets/font/iconfont.woff'
import iconFontTtf from '@/assets/font/iconfont.ttf'

/**
 * 初始化图标字体和样式
 * 将字体文件和相关样式注入到页面头部
 */
function init() {
    // 创建dom的style元素
    const style = document.createElement('style');

    /**
     * fontFace: 定义YRen-iconfont字体族，设置不同格式的字体源
     * baseStyle: 设置图标字体的基本样式（字体族、大小、抗锯齿等）
     * iconStyle: 定义具体图标的 Unicode 编码
     */
        // 使用导入的字体文件URL
    const fontFace = `
    @font-face {
      font-family: "YRen-iconfont";
      src: url('${iconFontWoff2}') format('woff2'),
           url('${iconFontWoff}') format('woff'),
           url('${iconFontTtf}') format('truetype');
    }
  `;

    // 基础样式：设置图标的通用样式属性
    // font-family: "my-iconfont" !important;   使用自定义的图标字体族
    // font-size: 16px;                         设置图标默认大小
    // font-style: normal;                      防止图标被斜体化
    // -webkit-font-smoothing: antialiased;     Webkit 浏览器抗锯齿
    // -moz-osx-font-smoothing: grayscale;      Firefox 浏览器抗锯齿
    const baseStyle = `
    .iconfont {
      font-family: "YRen-iconfont" !important;
      font-size: 16px;
      font-style: normal;
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
    }
  `;

// 图标样式：定义每个图标的Unicode编码
    const iconStyle = `
.icon-r-huowu:before {
  content: "\\e801";
}

.icon-r-gerenzhongxin:before {
  content: "\\e61d";
}

.icon-r-refresh:before {
  content: "\\ec99";
}

.icon-r-paper:before {
  content: "\\e61f";
}

.icon-r-building:before {
  content: "\\e600";
}

.icon-r-jurassic_user:before {
  content: "\\e6a5";
}

.icon-r-qingdanxinxishebeijichuxinxigongdanxinxi:before {
  content: "\\e64a";
}

.icon-r-tuandui:before {
  content: "\\e62d";
}

.icon-r-remen:before {
  content: "\\e8c9";
}

.icon-r-no:before {
  content: "\\e63a";
}

.icon-r-UIsheji_menjinxitong_huaban1:before {
  content: "\\e623";
}

.icon-r-shield:before {
  content: "\\e85c";
}

.icon-r-add:before {
  content: "\\e63e";
}

.icon-r-tianjia:before {
  content: "\\e64f";
}

.icon-r-user2:before {
  content: "\\f141";
}

.icon-r-edit:before {
  content: "\\e63f";
}

.icon-r-bianji1:before {
  content: "\\e60c";
}

.icon-r-renwuzhongxin:before {
  content: "\\e604";
}

.icon-r-test:before {
  content: "\\e601";
}

.icon-r-setting:before {
  content: "\\e622";
}

.icon-r-home:before {
  content: "\\e726";
}

.icon-r-user1:before {
  content: "\\e6ab";
}

.icon-r-manageUsers:before {
  content: "\\e61a";
}

.icon-r-l-find-copy:before {
  content: "\\f142";
}

.icon-r-delete:before {
  content: "\\e61c";
}

.icon-r-yes:before {
  content: "\\e679";
}

.icon-r-find:before {
  content: "\\e761";
}

.icon-r-lock:before {
  content: "\\e83e";
}

.icon-r-left-copy:before {
  content: "\\e8d4";
}

.icon-r-right-copy:before {
  content: "\\e8d5";
}
  `;
    style.innerHTML = fontFace + baseStyle + iconStyle;
    document.head.appendChild(style);
}

/**
 *  节流控制，防止频繁触发
 */
let isThrottled = true;
const throttleTime = 10;

/**
 * 需要处理的HTML标签或类名
 */
const tagList = ["button", ".el-menu-item", ".el-submenu__title", ".welcome"];

/**
 * 图标映射配置
 * key: 图标名称
 * text: 触发图标的文本数组
 * defaultSize: 图标和文本的默认大小
 */
const iconMap = {
    add: {
        text: ['新增', '添加', '创建', '录入', '导出', '上传', '注册'],
        defaultSize: {
            text: 16,
            icon: 18
        }
    },
    edit: {
        text: ['编辑', '修改'],
        defaultSize: {
            text: 16,
            icon: 18
        }
    },
    delete: {
        text: ['删除', '移除', '清空'],
        defaultSize: {
            text: 16,
            icon: 18
        }
    },
    yes: {
        text: ['确定', '支付', '提交', '下载', '发货', '登录'],
        defaultSize: {
            text: 16,
            icon: 18
        }
    },
    no: {
        text: ['取消', '返回'],
        defaultSize: {
            text: 16,
            icon: 18
        }
    },
    find: {
        text: ['查询', '搜索'],
        defaultSize: {
            text: 16,
            icon: 18
        }
    },
    refresh: {
        text: ['重置', '重置密码'],
        defaultSize: {
            text: 16,
            icon: 18
        }
    },
    paper: {
        text: ['详情',],
        defaultSize: {
            text: 16,
            icon: 18
        }
    },

};


/**
 * 加载图标的主函数
 * @param {string[]} excludeTexts - 不需要添加图标的文本数组
 */
export function loadIcons(excludeTexts) {
    if (!Array.isArray(excludeTexts)) {
        excludeTexts = [];
    }

    if (isThrottled) {
        setTimeout(() => {
            tagList.forEach(tag => {
                handleTag(tag, excludeTexts);
            });
        }, 10);

        isThrottled = false;
        setTimeout(() => {
            isThrottled = true;
        }, throttleTime);
    }
}

function handleTag(tagName, excludeTexts) {
    let elements;
    if (tagName.startsWith('#')) {
        const el = document.getElementById(tagName.substr(1));
        elements = el ? [el] : [];
    } else if (tagName.startsWith('.')) {
        elements = document.getElementsByClassName(tagName.substr(1));
    } else {
        elements = document.getElementsByTagName(tagName);
    }

    Array.from(elements).forEach(el => {
        if (shouldExclude(el, excludeTexts)) {
            return;
        }
        const text = el.textContent.trim();
        Object.entries(iconMap).forEach(([iconName, config]) => {
            if (config.text.some(t => text.includes(t))) {
                // 调用下方方法检查是否已经包含指定的图标，如没有给元素添加图标
                if (!hasIcon(el, iconName)) {
                    addIcon(el, iconName, config.defaultSize);
                }
            }
        });
    });
}

function shouldExclude(el, excludeTexts) {
    return excludeTexts.some(text => el.textContent.includes(text));
}

//检查元素是否已经包含指定的图标
function hasIcon(el, iconName) {
    const iconClass = `icon-r-${iconName}`;
    return el.querySelector(`.${iconClass}`);
}

//给元素添加图标
function addIcon(el, iconName, size) {
    const icon = document.createElement('i');
    icon.className = `iconfont icon-r-${iconName}`;
    icon.style.fontSize = `${size.icon}px`;
    el.style.fontSize = `${size.text}px`;

    if (el.firstChild) {
        el.insertBefore(icon, el.firstChild);
    } else {
        el.appendChild(icon);
    }
}

// 初始化
(function () {
    init();
})();

// Vue集成
Vue.mixin({
    //mounted在组件挂载到 DOM 后执行
    mounted() {
        //this.$nextTick()确保 DOM 已经完全更新
        this.$nextTick(() => {
            loadIcons();
        });
    }
});